import java.net.*;
import java.io.*;
import java.util.*;

public class ServerTalk {
   public static void main(String args[] ) {
     Vector vecIn = new Vector();
     Vector vecOut = new Vector();
     try {
 	ServerSocket ssk = new ServerSocket(8900);
	int anum = 1;
	
	ServerAgent agent = new ServerAgent(vecIn, vecOut);
	agent.start();

	while ( true ) {
		Socket sk = ssk.accept();
		vecIn.add(sk.getInputStream());
		vecOut.add(sk.getOutputStream());
		anum ++;
	}
      } catch (Exception e) { e.printStackTrace(); }
   }
}

class ServerAgent extends Thread {

   Vector vIn, vOut;
   public ServerAgent( Vector in, Vector out ) { vIn = in; vOut = out; }

   public void run() {
        byte inMsg[] = new byte[100], outMsg[] = new byte[100];
 	String msg = "Sender: agent  Message #: ";
	String str = null;
	int    num = 1, len;
     try {
	while ( true ) {
	     if ( vOut.size() > 0 ) {
		str = msg + (num++);
		outMsg = str.getBytes();
	     }
	     for ( int i = 0; i < vOut.size(); i ++ ) {
		((OutputStream ) vOut.get(i)).write( outMsg, 0, str.length());
	     }

	     for ( int i = 0; i < vIn.size(); i ++ )
		if ( ((InputStream ) vIn.get(i)).available() > 0 ) {
			len = ((InputStream) vIn.get(i)).read(inMsg);
			System.out.println("Receiver: agent " +
				",  " + new String(inMsg, 0, len));
		}

		Thread.sleep((int) ( Math.random() * 2000) );
	}
     } catch ( Exception e ) { e.printStackTrace(); }
   }

}
